//
//  PersonalInfoViewController.m
//  JiuJiuShangCheng
//
//  Created by jiujiukeji on 2018/7/9.
//  Copyright © 2018年 jiujiukeji. All rights reserved.
//

#import "PersonalInfoViewController.h"
#import "PersonalInfoTableViewCell.h"
#import "HSDatePickerVC.h"

@interface PersonalInfoViewController ()<UITableViewDelegate,UITableViewDataSource,HSDatePickerVCDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,TZImagePickerControllerDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UITextField *dateTF;
@property (nonatomic, strong) UITextField *nameTF;
@property (nonatomic, strong) UITextField *addressTF;
@property (nonatomic, strong) NSDictionary *personalInfoDic;
@property (nonatomic, strong) NSMutableArray *btnArray;
@property (nonatomic, assign) NSInteger selectIndex;
@property (nonatomic, strong) UIImage *headImg;
@property (nonatomic, strong) UIImageView *headImgV;
@property (nonatomic, strong) NSString *sex;

@end

@implementation PersonalInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = UIColorFromRGB(0xf5f5f5);
    [self loadBaseTitleLable:@"个人资料"];
    self.selectIndex = 0;
    [self.view addSubview:self.tableView];
    [self getPersonalInfo];
}
#pragma mark - 获取个人信息
- (void)getPersonalInfo
{
    NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
    [MBProgressHUD showMessage:nil toView:self.view];
    [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/member/member.ashx?action=memberinfo&companyid=%@&code=%@&timestamp=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp]] parameters:nil success:^(id responseObject) {
        [MBProgressHUD hideHUDForView:self.view];
        
        if ([responseObject[@"status"] intValue] == 1) {
            NSLog(@"个人信息");
            self.personalInfoDic = responseObject;
            [self.tableView reloadData];
        } else {
            [TFHUD addRemindHUD:self.view message:responseObject[@"returnMsg"]];
        }
        
    } failure:^(NSError *error) {
        [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
        
    }];
}
#pragma mark - 个人资料修改
- (void)changePersonalInfo
{
    NSLog(@"------%@",self.sex);
    NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
    [MBProgressHUD showMessage:nil toView:self.view];
    [TFNetworking postWithURLString:[NSString stringWithFormat:@"%@/api/json/member/member.ashx?action=editinfo&companyid=%@&code=%@&timestamp=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp]] parameters:@{@"input":@"memberZsname,memberBirthday,memberAddress,memberSex",@"memberZsname":_nameTF.text,@"memberBirthday":_dateTF.text,@"memberAddress":_addressTF.text,@"memberSex":self.sex} success:^(id responseObject) {
        [MBProgressHUD hideHUDForView:self.view];
        if (responseObject) {
            [TFHUD addRemindHUD:self.view message:responseObject[@"returnMsg"]];
            if ([responseObject[@"status"] intValue] == 1) {
                [self.navigationController popViewControllerAnimated:YES];
            }
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
    }];
}
#pragma mark - tableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    PersonalInfoTableViewCell *cell = [[PersonalInfoTableViewCell alloc] init];
    cell.contentView.backgroundColor = UIColorFromRGB(0xf5f5f5);
    NSArray *array = @[@"真实姓名",@"出生日期",@"性        别",@"家庭住址"];
    cell.leftLB.text = array[indexPath.row];
    if (indexPath.row == 0) {
        // 真实姓名
        cell.textField.text = self.personalInfoDic[@"nickName"];
        self.nameTF = cell.textField;
    } else if (indexPath.row == 3) {
        // 家庭住址
        cell.textField.text = self.personalInfoDic[@"address"];
        self.addressTF = cell.textField;
    }
    if (indexPath.row == 1) {
        // 出生日期
        cell.textField.enabled = NO;
        cell.textField.text = self.personalInfoDic[@"birthday"];
        self.dateTF = cell.textField;
    }
    if (indexPath.row == 2) {
        // 性别
        cell.rightBgImg.hidden = YES;
        cell.textField.hidden = YES;
        UIButton *btn1 = [UIButton buttonWithTitle:@"  保密" fontSize:13 titleColor:UIColorFromRGB(0x909090) background:kClearColor cornerRadius:0];
        [btn1 setImage:UIImageNamed(@"shemoren") forState:(UIControlStateNormal)];
        [cell.contentView addSubview:btn1];
        [btn1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(cell.leftLB.mas_right).offset(rateWidth(20));
            make.size.mas_offset(CGSizeMake(rateWidth(120), rateWidth(50)));
            make.centerY.equalTo(cell.contentView);
        }];
        UIButton *btn2 = [UIButton buttonWithTitle:@"  男" fontSize:13 titleColor:UIColorFromRGB(0x909090) background:kClearColor cornerRadius:0];
        [btn2 setImage:UIImageNamed(@"shemoren") forState:(UIControlStateNormal)];
        [cell.contentView addSubview:btn2];
        [btn2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(btn1.mas_right).offset(rateWidth(20));
            make.size.mas_offset(CGSizeMake(rateWidth(120), rateWidth(50)));
            make.centerY.equalTo(cell.contentView);
        }];
        UIButton *btn3 = [UIButton buttonWithTitle:@"  女" fontSize:13 titleColor:UIColorFromRGB(0x909090) background:kClearColor cornerRadius:0];
        [btn3 setImage:UIImageNamed(@"shemoren") forState:(UIControlStateNormal)];
        [cell.contentView addSubview:btn3];
        [btn3 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(btn2.mas_right).offset(rateWidth(20));
            make.size.mas_offset(CGSizeMake(rateWidth(120), rateWidth(50)));
            make.centerY.equalTo(cell.contentView);
        }];
        btn1.tag = 1;
        btn2.tag = 2;
        btn3.tag = 3;
        [btn1 addTarget:self action:@selector(selectSex:) forControlEvents:(UIControlEventTouchUpInside)];
        [btn2 addTarget:self action:@selector(selectSex:) forControlEvents:(UIControlEventTouchUpInside)];
        [btn3 addTarget:self action:@selector(selectSex:) forControlEvents:(UIControlEventTouchUpInside)];
        self.btnArray = [NSMutableArray array];
        [self.btnArray addObject:btn1];
        [self.btnArray addObject:btn2];
        [self.btnArray addObject:btn3];
        
        if (self.selectIndex != 0) {
            for (UIButton *button in self.btnArray) {
                if (button.tag == self.selectIndex) {
                    [button setImage:UIImageNamed(@"shemoren1") forState:(UIControlStateNormal)];
                } else {
                    [button setImage:UIImageNamed(@"shemoren") forState:(UIControlStateNormal)];
                }
            }
            
        } else {
            if ([self.personalInfoDic[@"sex"] intValue] == 1) {
                // 男
                [btn2 setImage:UIImageNamed(@"shemoren1") forState:(UIControlStateNormal)];
                self.sex = @"1";

            } else if ([self.personalInfoDic[@"sex"] intValue] == 2) {
                // 女
                [btn3 setImage:UIImageNamed(@"shemoren1") forState:(UIControlStateNormal)];
                self.sex = @"2";
            } else {
                // 保密
                [btn1 setImage:UIImageNamed(@"shemoren1") forState:(UIControlStateNormal)];
                self.sex = @"0";
            }
        }
    }
    cell.selectionStyle = NO;
    return cell;
}
- (void)selectSex:(UIButton *)btn
{
    for (UIButton *button in self.btnArray) {
        self.selectIndex = btn.tag;
        if (button.tag == btn.tag) {
            [button setImage:UIImageNamed(@"shemoren1") forState:(UIControlStateNormal)];
        } else {
            [button setImage:UIImageNamed(@"shemoren") forState:(UIControlStateNormal)];
        }
        if (self.selectIndex == 1) {
            self.sex = @"0";
        } else if (self.selectIndex == 2) {
            self.sex = @"1";
        } else if (self.selectIndex == 3) {
            self.sex = @"2";
        }
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return rateWidth(120);
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return rateWidth(540);
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return rateWidth(300);
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *bgV = [[UIView alloc] init];
    bgV.backgroundColor = UIColorFromRGB(0xf5f5f5);
    UIView *redV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, rateWidth(520))];
    redV.backgroundColor = navBarColor;
    [bgV addSubview:redV];
    UIImageView *headBgImg = [[UIImageView alloc] init];
    headBgImg.image = UIImageNamed(@"headBgImg");
    [headBgImg sizeToFit];
    [redV addSubview:headBgImg];
    [headBgImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(redV);
        make.top.equalTo(redV).offset(rateWidth(40));
    }];
    UIImageView *headImg = [[UIImageView alloc] init];
    if (self.headImg) {
        headImg.image = self.headImg;
    } else {
        if ([[self.personalInfoDic[@"memberImg"] substringToIndex:5] isEqualToString:@"http:"]) {
            [headImg sd_setImageWithURL:[NSURL URLWithString:self.personalInfoDic[@"memberImg"]]];
        } else {
            [headImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http:%@",self.personalInfoDic[@"memberImg"]]]];
        }
    }
    headImg.layer.masksToBounds = YES;
    headImg.layer.cornerRadius = rateWidth(110);
    [headBgImg addSubview:headImg];
    [headImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_offset(CGSizeMake(rateWidth(220), rateWidth(220)));
        make.center.equalTo(headBgImg);
    }];
    self.headImgV = headImg;
    // 修改头像
    UIButton *changeBtn = [UIButton buttonWithTitle:@"修改头像" fontSize:13 titleColor:UIColorFromRGB(0xf55555) background:UIColorWhite cornerRadius:3];
    [redV addSubview:changeBtn];
    [changeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_offset(CGSizeMake(rateWidth(190), rateWidth(60)));
        make.top.equalTo(headBgImg.mas_bottom).offset(rateWidth(40));
        make.centerX.equalTo(redV);
    }];
    [changeBtn addTarget:self action:@selector(pushImagePickerController) forControlEvents:(UIControlEventTouchUpInside)];
    
    return bgV;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *bgV = [[UIView alloc] init];
    bgV.backgroundColor = UIColorFromRGB(0xf5f5f5);
    UIButton *btn = [UIButton buttonWithTitle:@"提交" fontSize:16 titleColor:UIColorWhite background:navBarColor cornerRadius:6];
//    UIButton *btn = [UIButton buttonWithType:(UIButtonTypeCustom)];
//    [btn setImage:UIImageNamed(@"ziliaotijiao") forState:(UIControlStateNormal)];
//    [btn sizeToFit];
    [bgV addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(bgV);
        make.top.equalTo(bgV).offset(rateWidth(40));
        make.size.mas_offset(CGSizeMake(rateWidth(700), rateWidth(80)));
    }];
    [btn addTarget:self action:@selector(changePersonalInfo) forControlEvents:(UIControlEventTouchUpInside)];
    
    return bgV;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 1) {
        // 出生日期
        HSDatePickerVC *vc = [[HSDatePickerVC alloc] init];
        vc.delegate = self;
        [self presentViewController:vc animated:YES completion:nil];
    }
}
#pragma mark - HSDatePickerVCDelegate
- (void)datePicker:(HSDatePickerVC*)datePicker
          withYear:(NSString *)year
             month:(NSString *)month
               day:(NSString *)day
{
    self.dateTF.text = [NSString stringWithFormat:@"%@-%@-%@",year,month,day];
    NSLog(@"选择了   %@--%@--%@",year,month,day);
}
#pragma mark - TZImagePickerController
- (void)pushImagePickerController {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:3 delegate:self pushPhotoPickerVc:YES];
    
    imagePickerVc.allowTakePicture = YES; // 在内部显示拍照按钮
    
    // 2. Set the appearance
    // 2. 在这里设置imagePickerVc的外观
    imagePickerVc.navigationBar.barTintColor = navBarColor;
    imagePickerVc.oKButtonTitleColorDisabled = navBarColor;
    imagePickerVc.oKButtonTitleColorNormal = navBarColor;
    imagePickerVc.navigationBar.translucent = NO;
    
    // 3. Set allow picking video & photo & originalPhoto or not
    // 3. 设置是否可以选择视频/图片/原图
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingOriginalPhoto = NO;
    imagePickerVc.allowPickingGif  = YES;
    
    // 4. 照片排列按修改时间升序
    imagePickerVc.sortAscendingByModificationDate = YES;
    imagePickerVc.allowCrop = YES;
    imagePickerVc.needCircleCrop = NO;
    imagePickerVc.cropRect = CGRectMake((kScreenWidth-rateWidth(520))/2, (kScreenHeight-rateWidth(520))/2, rateWidth(520), rateWidth(520));
    [imagePickerVc setCropViewSettingBlock:^(UIView *cropView) {
        cropView.layer.borderColor = navBarColor.CGColor;
        cropView.layer.borderWidth = 0.5;
    }];
    
    //imagePickerVc.allowPreview = NO;
#pragma mark - 到这里为止
    
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    __weak typeof(self) weakSelf = self;
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        weakSelf.headImgV.image = photos[0];
        weakSelf.headImg = photos[0];
        [weakSelf updateHeadPhoto:photos[0]];
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}
#pragma mark - 上传头像
- (void)updateHeadPhoto:(UIImage *)image
{
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    if (_headImg) {
        UIImage *image = _headImg;
        NSData *data = UIImageJPEGRepresentation(image, 0.1);
        NSString * imageStr = [data  base64EncodedStringWithOptions:0];
        
        [parameters setValue:imageStr forKey:@"face"]; // 头像
        NSLog(@"%@",parameters);
        [MBProgressHUD showMessage:nil toView:self.view];
        NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
        [TFNetworking postWithURLString:[NSString stringWithFormat:@"%@/api/json/member/member.ashx?action=memberface&companyid=%@&code=%@&timestamp=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp]] parameters:parameters success:^(id responseObject) {
            [MBProgressHUD hideHUDForView:self.view];
            NSLog(@"修改头像：%@",responseObject);
            if (responseObject) {
                if ([responseObject[@"status"] intValue] == 1) {
                    // 修改成功
                    [MBProgressHUD showSuccess:@"修改成功"];
                    [self.navigationController popViewControllerAnimated:YES];
                }
            }
            
        } failure:^(NSError *error) {
            NSLog(@"%@",error);
            [TFHUD addRemindHUD:self.view message:@"保存失败,请检查网络"];
        }];
    }
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight, kScreenWidth, kScreenHeight-SafeAreaTopHeight-SafeAreaBottomHeight) style:(UITableViewStyleGrouped)];
        _tableView.backgroundColor = UIColorFromRGB(0xf5f5f5);
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = NO;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
    }
    return _tableView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
